<template>
	<div class="w-100">
		<ul>
			<li v-for="(v, k) in groupObj" :key="k">
				<p class="node-label mt10">{{ k }}</p>
				<el-checkbox-group v-model="selected" @change="handleSelect">
					<el-checkbox :label="chi.name" :value="chi.name" v-for="chi in v" :key="chi.name"></el-checkbox>
				</el-checkbox-group>
			</li>
		</ul>

		<el-tabs class="mt10" type="border-card">
			<el-tab-pane v-for="(item, index) in checkedList" :key="index" :label="item.name" :name="item.name">
				<Statistics :dragData="item" @cell-change="handleCondition"></Statistics>
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script setup lang="ts">
import { groupBy } from 'lodash-es'
import Statistics from '../StatisticsPage/index.vue'
import { useCommonStore } from '@/stores/common'

const { tempNowObj } = storeToRefs(useCommonStore())

type Props = {
	baseType: string | number
	dragData?:any
}
const props = withDefaults(defineProps<Props>(), {})
const emit = defineEmits(['field-change'])
const groupObj: any = ref({})
const activeNames = ref([''])

const selected = ref([])
const checkedList = ref([])
const checkedModel = ref({})
watch(
	() => props.baseType,
	(val) => {
		const dataList = tempNowObj.value || []
		const list = dataList.length > 0 ? dataList.filter((item) => item.name !== val) : [] // 排除自身
    const tempArr = list.map(item=> {
      const temp = props.dragData?.associatedFields?.find(i => i.tableName === item.tableName)
      if(temp) {
        return item
      }
    }).filter(Boolean)
		groupObj.value = groupBy(tempArr, 'typeName')
		activeNames.value = Object.keys(groupObj.value)
	},
	{
		immediate: true,
	}
)

const handleSelect = (e) => {
	checkedList.value = tempNowObj.value.filter((item) => selected.value.includes(item.name))
}

const handleCondition = (cell, item) => {
	checkedModel.value[item.name] = cell
	emit('field-change', checkedModel.value, checkedList.value)
}
</script>

<style scoped></style>
